const app = getApp();
const api = require('../../../ws_micro_shop/utils/api.js');
const { handleStatisticsShare, wxappjump } = require('../../api/common');

Page({
  data: {
    toView: '',
    useTabbar: !(app.tabbarindex === 0 && app.siteInfo.tabbar_type === '1'),
    menuCurrentIndex: 0,
    shareInfo: {
      birthday_greeting: 0,
      advertising: {
        data: [],
        new: 0,
      },
      comsumer_return: {
        data: [],
        new: 0,
      },
      goods_list: {
        list: [],
        new: 0,
      },
      guide_coupon: [],
      topic: {
        list: [],
        new: 0,
      },
      param_id:'',
      type:''
    },
    isWXWork: app.isWXWork,
    isShowMask: false,
    followUpText: '',
    customerId: '',
    articleCurrentIndex: 0,
    isShow: false,
    birthday: '',
    visit: '',
    coupon: '',
    goods: '',
    article: '',
    poster: '',
    shopid:'',
    guide_id: '',
    share_modal_active: '',
    imgUrl: app.imgUrl
  },
  
  onLoad() {
    wx.hideShareMenu();
    let that = this;
    let access_token = wx.getStorageSync('access_token');
    if (access_token && app.isWXWork) {
      app.qyCheckSession({
        success: () => {
          that.init();
        },
        fail: err => {
          console.log('企业微信登录失败', err);
        },
      });
    } else {
      app.ws_micro_shoplogin().then(res => {
        that.init();
      });
    }
  },
  onShow() {
    this.setData({
      shopid: app.ws_micro_shop_globalData.shopid,
      guide_id: app.ws_micro_shop_globalData.guide_id,
      isSaas: app.ws_micro_shop_globalData.isSaas,
      role: app.ws_micro_shop_globalData.role,
      goods_qrcode_active: '',
      share_modal_active: '',
      goods_qrcode: ''
    });
  },

  onPullDownRefresh() {
    wx.showLoading({
      title: '正在加载',
    });
    wx.showNavigationBarLoading();
    this.onLoad();
    setTimeout(function () {
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
      wx.hideLoading();
    }, 1500);
  },

  init() {
    let that = this;
    that.setData({
      shopid: app.ws_micro_shop_globalData.shopid,
      guide_id: app.ws_micro_shop_globalData.guide_id,
      isSaas: app.ws_micro_shop_globalData.isSaas,
      role: app.ws_micro_shop_globalData.role
    },()=>{
      that.getShareInfo();
    });
  },

  getShareInfo() {
    let that = this;
    wx.showLoading({
      title: '正在加载...',
      mask: true,
    });
    app.ws_micro_shoprequest({
      url: api.staff.share,
      data: {
        type: 1
      },
      success: res => {
        if (res && res.code === 0 && res.data) {
          that.setData({
            shareInfo: res.data,
            isShow: true,
          });
          that.getPosterLists();
        }
      },
      complete: res => {
      },
    });
  },
  getPosterLists() {
    let that = this;
    let openid = wx.getStorageSync('OPENID') || wx.getStorageSync('openid');
    app.util.request({
      url: 'wxapp/poster/getPosterLists',
      data: {
        page: 1,
        categoryid: 0,
        categorysubid: '',
        openid,
        fw : 'micro_shop_B',
        corpid: wx.getStorageSync('corpid'),
        bindacid: wx.getStorageSync('cor_uniacid') || 0,
      },
      method: 'POST',
      success: function(res) {
        if (res.statusCode === 200) {
          if (res.data) {
            that.setData({
              [`shareInfo.advertising`]: {
                data: res.data.result,
                new: res.data.total
              }
            });
          }
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    });
  },

  onNavigate(e) {
    const { url, ...params } = e.currentTarget.dataset;
    url && app.util.navigateTo(url, params);
  },

  showEdit(e) {
    let {
      tmpid,
      type,
      index,
      item
    } = e.currentTarget.dataset;
    wx.setStorageSync('posterDetail', item);
    app.util.navigateTo('/common/page/editPoster/index', {
      type,
      tmpid,
    })
  },


  onShareAppMessage(e) {
    if (e.from === 'button') {
    let { imageurl: imageUrl = '', title = '', path, param_id, type='', share_title = '', share_pic = '' } = e.target.dataset;
    const { shopid,guide_id } = this.data;
    const finalPath = path + '&shopid=' + shopid + '&guide_id=' + guide_id;
    title = Number(type) === 7 ? share_title : title
    imageUrl = Number(type) === 7 ? share_pic : imageUrl
    this.setData({
      param_id,
      type
    })
      return {
        title,
        path:finalPath,
        imageUrl,
      };
    }
  },

  onUserOpStatistic(e) {
    // if (String(e.op) === 'share') {
      const { param_id = '',type='' } = this.data;
      handleStatisticsShare({ type, param_id });
    // }
    wx.hideLoading();
  },

  showShareModal(e) {
    let dataset = e.target.dataset;
    this.setData({
      ...dataset,
      share_modal_active: 'active',
    });
  },

  shareModalClose() {
    this.setData({
      share_modal_active: '',
    });
  },

  wxappJump() {
    let { titletype, path, shopid, guide_id, type, param_id } = this.data;
    let appid =  wx.getStorageSync('appid');
    let share_type = Number(type) === 6 ? 0 : Number(type);
    path = path + '&shopid=' + shopid + '&guide_id=' + guide_id + '&num=' + share_type;
    if (Number(type) === 7) {
      path = path + '&from=fromB';
    }
    console.info('-------path---------', path);
    wxappjump(appid, path, type, param_id, this);
  },
  
  getGoodsQrcode() {
    let _this = this;
    
    let { param_id = '', guide_id = '', goods_qrcode = '', share_pic = '', imageurl = '', type } = _this.data;
    _this.setData({
      goods_qrcode_active: 'active',
    });
    if (goods_qrcode) {
      return true;
    }
    let url = Number(type) === 7 ?  api.staff.topic_qrcode : api.staff.goods_qrcode;
    let data = Number(type) === 7 ? {
      id: param_id,
      guide_id: guide_id,
      share_type: 7,
    } : {
      goods_id: param_id,
      guide_id: guide_id,
      share_type: type,
      cover_pic: imageurl
    }
    app.ws_micro_shoprequest({
      url,
      data,
      success: function(res) {
        if (res.code === 0) {
          _this.setData({
            goods_qrcode: res.data.pic_url,
          });
          handleStatisticsShare({ type, param_id });
        }
        if (res.code === 1) {
          _this.goodsQrcodeClose();
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
          });
        }
      },
    });
  },

  goodsQrcodeClose() {
    this.setData({
      goods_qrcode_active: '',
      share_modal_active: '',
      goods_qrcode: ''
    });
  },
  saveGoodsQrcode() {
    let _this = this;
    if (!wx.saveImageToPhotosAlbum) {
      wx.showModal({
        title: '提示',
        content:
          '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
        showCancel: false,
      });
      return;
    }
    wx.getSetting({
      success(res) {
        if (typeof res.authSetting['scope.writePhotosAlbum'] === 'undefined') {
          _this.downLoadGoodsImg();
        } else if (res.authSetting['scope.writePhotosAlbum'] === false) {
          _this.setData({
            open_setting: true,
          });
        } else {
          _this.downLoadGoodsImg();
        }
      },
    });
  },
  downLoadGoodsImg() {
    let _this = this;
    let { type } = _this.data;
    wx.showLoading({
      title: '正在下载图片',
      mask: true,
    });
    wx.downloadFile({
      url: _this.data.goods_qrcode,
      success: function(e) {
        wx.showLoading({
          title: '正在保存图片',
          mask: true,
        });
        wx.saveImageToPhotosAlbum({
          filePath: e.tempFilePath,
          success: function() {
            wx.showModal({
              title: '提示',
              content: Number(type) === 7 ? '软文海报保存成功' : '商品海报保存成功',
              showCancel: false,
            });
          },
          fail: function(e) {
            wx.showModal({
              title: '提示',
              content: '图片保存失败',
              showCancel: false,
            });
          },
          complete: function(e) {
            wx.hideLoading();
          },
        });
      },
      fail: function(e) {
        wx.showModal({
          title: '图片下载失败',
          content: e.errMsg + ';' + _this.data.goods_qrcode,
          showCancel: false,
        });
      },
      complete: function(e) {
        wx.hideLoading();
      },
    });
  },

  goodsQrcodeClick(e) {
    let src = e.currentTarget.dataset.src;
    wx.previewImage({
      urls: [src],
    });
  },
});
